package com.tzbank.voice.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.Calendar;

/**
 * 
 */
public class FileUploadUtil {

    public static String upload(MultipartFile file, String path) throws Exception{
        if(file==null){
            throw new Exception("file is null");
        }
        if(path==null){
            throw new Exception("file path is null");
        }
		Calendar cal = Calendar.getInstance();
		String year = String.valueOf(cal.get(1));
		String month = String.valueOf(cal.get(2) + 1);
	    String day = String.valueOf(cal.get(5));
    	//String oldName = file.getOriginalFilename();
        //获取文件的后缀名
        String fileName = file.getOriginalFilename();
        //String suffix = fileName+fileName.substring(fileName.lastIndexOf("."));
        String filePath = path+"/File";
        String filePathand = path+"/File/upLoad/"+fileName;
        File f = new File(filePath,fileName);
        if(!f.getParentFile().exists()){
            f.getParentFile().mkdirs();
            f.createNewFile();
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(),f);
        return filePathand;
    }

    /**
     * 获得指定文件的byte数组
     */

    public static byte[] getBytes(String filePath) throws Exception{
        byte[] buffer = null;
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
        byte[] b = new byte[1000];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        if(fis!=null){
            fis.close();
        }
        if(bos!=null){
            bos.close();
        }
        buffer = bos.toByteArray();
        return buffer;
    }
}
